package com.syni.mdd.yhd.common.all.service.impl;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.yhd.common.all.utils.LocationUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsChatAnnounDao;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsDxGroupChatDao;
import com.syni.mdd.yhd.common.all.dto.requestDto.groupChart.ChatAnnounReDto;
import com.syni.mdd.yhd.common.all.dto.requestDto.groupChart.GroupChatReDto;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.groupChat.BmsChatAnnoun;
import com.syni.mdd.yhd.common.all.entity.groupChat.BmsDxGroupChat;
import com.syni.mdd.yhd.common.all.entity.groupChat.BmsUserChat;
import com.syni.mdd.yhd.common.all.entity.record.ReGoupChat;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.listen.groupShare.GroupShareEvent;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.groupChat.BmsChatAnnounService;
import com.syni.mdd.yhd.common.all.service.groupChat.BmsUserChatService;
import com.syni.mdd.yhd.common.all.service.record.ReGoupChatService;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.utils.aurora.AuroraMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
public class BmsDxGroupChatServiceImpl extends BaseService<BmsDxGroupChat, Integer> implements BmsDxGroupChatService {

    @Autowired
    BmsDxGroupChatDao bmsDxGroupChatDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsChatAnnounDao bmsChatAnnounDao;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    BmsUserChatService bmsUserChatService;

    @Autowired
    BmsDxOrderStatusService bmsDxOrderStatusService;

    @Autowired
    BmsUserService bmsUserService;

    @Autowired
    BmsDxUserPermissionService bmsDxUserPermissionService;

    @Autowired
    BmsBusinessCouponService bmsBusinessCouponService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsChatAnnounService bmsChatAnnounService;

    @Autowired
    BmsMarketActivityService bmsMarketActivityService;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Autowired
    ReGoupChatService reGoupChatService;

    @Autowired
    BmsUserBusinessFocusService bmsUserBusinessFocusService;

    @Override
    public BmsDxGroupChatDao getBaseDao() {
        return bmsDxGroupChatDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> create(GroupChatReDto groupChatReDto) throws Exception {
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(Integer.parseInt(groupChatReDto.getUserId()),groupChatReDto.getBusinessId());
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        //判断店铺是否已经有群了
        List<BmsDxGroupChat> bmsDxGroupChats = bmsDxGroupChatDao.findByBusinessIdAndIsDelete(groupChatReDto.getBusinessId(),Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_EXIST,ResultMsg.CODE_GROUP_CHAT_IS_EXIST);
        }
        Map<String,Object> userDataMap = (Map<String, Object>) checkMap.get("userData");
        BmsUserBusinessAuth bmsUserBusinessAuth = (BmsUserBusinessAuth) userDataMap.get("businessAuth");
        BmsDxGroupChat bmsDxGroupChat = new BmsDxGroupChat();
        initDefaultAttribute(bmsDxGroupChat);
        BeanUtils.copyProperties(groupChatReDto,bmsDxGroupChat);
        if(!StringUtils.isNotBlank(bmsDxGroupChat.getGroupImg())){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.MSG_GROUP_IMG_NULL);
        }
        //查询该店铺店员（群人数 = 店员人数 + 管理员）
        bmsDxGroupChat.setGroupNum(bmsUserBusinessService.countMyBusinessAssistant(bmsDxGroupChat.getBusinessId()) + 1);
        bmsDxGroupChatDao.save(bmsDxGroupChat);
        bmsDxGroupChat.setGroupImg(String.format("%s?gid=%s&sid=%s",bmsDxGroupChat.getGroupImg(),bmsDxGroupChat.getId(),bmsDxGroupChat.getBusinessId()));
        //创建群成员
        List<BmsUserChat> bmsUserChats = postHandCreateGroupMember(bmsDxGroupChat,bmsUserBusinessAuth);
        //在极光创建群
        if(!postHandCreateChat(bmsDxGroupChat,bmsUserChats,bmsUserBusinessAuth.getBmsBusiness())){
            throw new Exception("群创建失败");
        }
        bmsDxGroupChatDao.save(bmsDxGroupChat);
        return ResultMapHelper.success(bmsDxGroupChat, ResultMsg.INSERT_SUCCESS);
    }

    /**
     * @Description 创建群成员（店主 + 店员）
     * @Author: cfx
     * @Date: 2019/10/8
     */
    private List<BmsUserChat> postHandCreateGroupMember(BmsDxGroupChat bmsDxGroupChat, BmsUserBusinessAuth bmsUserBusinessAuth) {
        Date nowTime = new Date();
        BmsBusiness business = bmsUserBusinessAuth.getBmsBusiness();
        //创建店主成员
        Integer businessManId = bmsUserBusinessAuth.getBmsUserId();
        List<BmsUserChat> bmsUserChats = new ArrayList<>();
        BmsUserChat bmsUserChat = new BmsUserChat();
        bmsUserChat.setUserId(businessManId);
        bmsUserChat.setRoleId(Constants.BUSINESS_ROLE_ID);
        bmsUserChat.setChatId(bmsDxGroupChat.getId());
        bmsUserChat.setBusinessId(bmsUserBusinessAuth.getBmsBusinessId());
        bmsUserChat.setNewTime(nowTime);
        bmsUserChat.setNameInGroupChat(business.getVendorName());
        bmsUserChats.add(bmsUserChat);
        //创建店员成员
        List<Map<String,Object>> assistantList = bmsUserBusinessService.getBaseDao().selfFindBusinessIdAndRoleId(business.getId(),Constants.ASSISTANT_ROLE_ID);
        if(assistantList != null && assistantList.size() > 0){
            for(Map<String,Object> assistant : assistantList){
                BmsUserChat assistantUserChat = new BmsUserChat();
                assistantUserChat.setUserId(Integer.parseInt(assistant.get("bms_user_id").toString()));
                assistantUserChat.setRoleId(Constants.ASSISTANT_ROLE_ID);
                assistantUserChat.setChatId(bmsDxGroupChat.getId());
                assistantUserChat.setBusinessId(bmsUserBusinessAuth.getBmsBusinessId());
                assistantUserChat.setNewTime(nowTime);
                assistantUserChat.setNameInGroupChat(assistant.get("name_in_store").toString());
                bmsUserChats.add(assistantUserChat);
            }
        }
        if(bmsUserChats != null && bmsUserChats.size() > 0){
            bmsUserChatService.getBaseDao().saveAll(bmsUserChats);
        }
        return bmsUserChats;
    }

    /**
     * @Description 创建极光群
     * @Author: cfx
     * @Date: 2019/10/8
     */
    private boolean postHandCreateChat(BmsDxGroupChat bmsDxGroupChat,List<BmsUserChat> bmsUserChats,BmsBusiness bmsBusiness) {
        if(bmsUserChats != null && bmsUserChats.size() > 0){
            //注册群成员
            AuroraMessageUtils.registerBusinessUsers(bmsUserChats,bmsBusiness);
            String adminName = null;
            List<String> memberName = new ArrayList<>();
            for(BmsUserChat bmsUserChat : bmsUserChats){
                if(bmsUserChat.getRoleId() == Constants.BUSINESS_ROLE_ID){
                    adminName = AuroraMessageUtils.USER_PREFIX + bmsUserChat.getUserId().toString();
                }else if(bmsUserChat.getRoleId() == Constants.ASSISTANT_ROLE_ID){
                    memberName.add(AuroraMessageUtils.USER_PREFIX + bmsUserChat.getUserId().toString());
                }
            }
            if(adminName != null){
                //创建群
                AuroraMessageUtils.createGroup(bmsDxGroupChat,adminName,memberName);
                if(StringUtils.isNotBlank(bmsDxGroupChat.getGid())){
                    //同时加入虚拟用户
                    //AuroraMessageUtils.addVirtualUser(bmsDxGroupChat.getGid());
                    return true;
                }
            }
        }
        return false;
    }

    private void initDefaultAttribute(BmsDxGroupChat bmsDxGroupChat) {
        bmsDxGroupChat.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
        bmsDxGroupChat.setGroupNum(Constants.COMMON_FLAG_FALSE_INT);
    }

    @Override
    public Map<String, Object> checkIsUpdateGroupName(GroupChatReDto groupChatReDto) {
        Integer id = groupChatReDto.getId();
        Optional<BmsDxGroupChat> bmsDxGroupChatOption = bmsDxGroupChatDao.findById(id);
        if(!bmsDxGroupChatOption.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        Date nowTime = new Date();
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChatOption.get();
        if(bmsDxGroupChat.getGroupNameUpdateTime() != null){
            Integer passTime = DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(bmsDxGroupChat.getGroupNameUpdateTime(),30));
            Integer startTime = DateTimeUtils.converDateToInterger(nowTime);
            if(passTime > startTime) {
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_CHAT_UPDATE_NAME_LIMIE, ResultMsg.CODE_BUSINESS_GROUP_CHAT_UPDATE_NAME_LIMIE);
            }
        }
        return ResultMapHelper.success(null,"ok");
    }

    @Override
    public Map<String, Object> update(GroupChatReDto groupChatReDto) {
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHavingOrAssistant(Integer.parseInt(groupChatReDto.getUserId()),groupChatReDto.getBusinessId());
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Integer id = groupChatReDto.getId();
        Optional<BmsDxGroupChat> bmsDxGroupChatOption = bmsDxGroupChatDao.findById(id);
        if(!bmsDxGroupChatOption.isPresent()) {
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST, ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChatOption.get();
        if(!bmsDxGroupChat.getGroupName().equals(groupChatReDto.getGroupName())){
            bmsDxGroupChat.setGroupNameUpdateTime(new Date());
        }
        BeanUtils.copyProperties(groupChatReDto,bmsDxGroupChat,BeanUtils.getNullPropertyNames(groupChatReDto));
        if(StringUtils.isNotBlank(bmsDxGroupChat.getGroupImg())){
            String[] groupChatImgs = bmsDxGroupChat.getGroupImg().split("\\?");
            if(groupChatImgs.length > 2){
                bmsDxGroupChat.setGroupImg(groupChatImgs[0]);
            }
        }
        bmsDxGroupChat.setGroupImg(String.format("%s?gid=%s&sid=%s",bmsDxGroupChat.getGroupImg(),bmsDxGroupChat.getId(),bmsDxGroupChat.getBusinessId()));
        bmsDxGroupChatDao.save(bmsDxGroupChat);
        //同步极光
        AuroraMessageUtils.updateGroupData(bmsDxGroupChat);
        return ResultMapHelper.success(bmsDxGroupChat,ResultMsg.UPDATE_SUCCESS);
    }

    /**
     * @Description 创建群公告
     * @Param ChatAnnounReDto
     * @return Map
     * @Author: cfx
     * @Date: 2019/9/9
     */
    public Map<String, Object> createAnnoun(ChatAnnounReDto chatAnnounReDto) {
        BmsChatAnnoun bmsChatAnnoun = new BmsChatAnnoun();
        bmsChatAnnoun.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
        bmsChatAnnoun.setAnnounType(Constants.CHAT_ANNOUN_TYPE_GEN);
        BeanUtils.copyProperties(chatAnnounReDto,bmsChatAnnoun);
        if(chatAnnounReDto.getBusinessCouponId() != null){
            Optional<BmsBusinessCoupon> bmsBusinessCoupon = bmsBusinessCouponService.getBaseDao().findById(chatAnnounReDto.getBusinessCouponId());
            if(bmsBusinessCoupon.isPresent()){
                BmsBusinessCoupon businessCoupon = bmsBusinessCoupon.get();
                bmsBusinessCouponService.setBusinessCoupons(businessCoupon);
                bmsChatAnnoun.setAnnounType(Constants.CHAT_ANNOUN_TYPE_COUPON);
                bmsChatAnnoun.setExtra(JSON.toJSONString(businessCoupon));
            }
        }
        if(chatAnnounReDto.getActivityId() != null){
            BmsMarketActivity bmsMarketActivity = bmsMarketActivityService.findById(chatAnnounReDto.getActivityId());
            if(bmsMarketActivity != null){
                bmsChatAnnoun.setAnnounType(Constants.CHAT_ANNOUN_TYPE_ACTIVITY);
                bmsChatAnnoun.setExtra(JSON.toJSONString(bmsMarketActivity));
            }
        }
        if(bmsChatAnnoun.getChatId() == null){
            //寻找第一个群
            List<BmsDxGroupChat> bmsDxGroupChats  = bmsDxGroupChatDao.findByBusinessIdAndIsDelete(chatAnnounReDto.getBusinessId(),Constants.COMMON_FLAG_FALSE_INT);
            if(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0){
                bmsChatAnnoun.setChatId(bmsDxGroupChats.get(0).getId());
            }
        }
        bmsChatAnnoun.setId(null);
        bmsChatAnnounDao.save(bmsChatAnnoun);
        return ResultMapHelper.success(bmsChatAnnoun, ResultMsg.INSERT_SUCCESS);
    }

    /**
     * @Description 查看群公告详情
     * @param chatAnnounReDto
     * @Data:2019/9/18
     */
    public Map<String, Object> findAnnounDetail(ChatAnnounReDto chatAnnounReDto) {
        Optional<BmsChatAnnoun> bmsChatAnnounOptional = bmsChatAnnounDao.findById(chatAnnounReDto.getId());
        if(!bmsChatAnnounOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.MSG_CHAT_ANNOUN_IS_NO_EXIST,ResultMsg.MSG_CHAT_ANNOUN_IS_NO_EXIST);
        }
        return ResultMapHelper.success(bmsChatAnnounOptional.get(),"OK");
    }

    /**
     * @Description 查看群公告列表
     * @param chatAnnounReDto
     * @Data:2019/9/18
     */
    public Map<String, Object> findAnnounList(ChatAnnounReDto chatAnnounReDto) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("chatId",chatAnnounReDto.getChatId());
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        Pageable pageable = BmsCommonService.getPageable(chatAnnounReDto.getPageNum(),chatAnnounReDto.getPageSize(), Sort.Direction.DESC,"newTime");
        Page<BmsChatAnnoun> bmsChatAnnounPage = bmsChatAnnounDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsChatAnnoun> bmsChatAnnounList = bmsChatAnnounPage.getContent();
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",bmsChatAnnounPage.getTotalElements());
        return ResultMapHelper.success(bmsChatAnnounList, userDataMap,"OK");
    }

    /**
     * @Description 查看群公告列表
     * @param chatAnnounReDto
     * @Data:2019/9/18
     */
    public Map<String, Object> userGetAnnounList(ChatAnnounReDto chatAnnounReDto) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("chatId",chatAnnounReDto.getChatId());
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        Date nowTime = new Date();
        Date conditionTime = DateTimeUtils.addMonth(nowTime,-1);
        conditionMap.put("newTime_GTT",conditionTime);
        Pageable pageable = BmsCommonService.getPageable(chatAnnounReDto.getPageNum(),chatAnnounReDto.getPageSize(), Sort.Direction.DESC,"newTime");
        Page<BmsChatAnnoun> bmsChatAnnounPage = bmsChatAnnounDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsChatAnnoun> bmsChatAnnounList = bmsChatAnnounPage.getContent();
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",bmsChatAnnounPage.getTotalElements());
        return ResultMapHelper.success(bmsChatAnnounList, userDataMap,"OK");
    }

    /**
     * @Description 删除群公告
     * @Param ChatAnnounReDto
     * @return Map
     * @Author: cfx
     * @Date: 2019/9/9
     */
    public Map<String, Object> deleteAnnoun(ChatAnnounReDto chatAnnounReDto) {
        Optional<BmsChatAnnoun> bmsChatAnnounOptional = bmsChatAnnounDao.findById(chatAnnounReDto.getId());
        if(!bmsChatAnnounOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.MSG_CHAT_ANNOUN_IS_NO_EXIST,ResultMsg.MSG_CHAT_ANNOUN_IS_NO_EXIST);
        }
        bmsChatAnnounDao.delete(bmsChatAnnounOptional.get());
        return ResultMapHelper.success(bmsChatAnnounOptional.get(),ResultMsg.DELETE_SUCCESS);
    }

    @Override
    public Map<String, Object> getBusinessGroupChat(GroupChatReDto groupChatReDto) {
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHavingOrAssistant(Integer.parseInt(groupChatReDto.getUserId()),groupChatReDto.getBusinessId());
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        //查询这家店的群聊列表
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("businessId",business.getId());
        List<BmsDxGroupChat> bmsDxGroupChatList = bmsDxGroupChatDao.findAll(new SpecificationUtils(conditionMap));
        return ResultMapHelper.success(bmsDxGroupChatList,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getBusinessGroupMembers(GroupChatReDto groupChatReDto) {
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHavingOrAssistant(Integer.parseInt(groupChatReDto.getUserId()),groupChatReDto.getBusinessId());
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        //获取群成员列表
        Pageable pageable = BmsCommonService.getPageable(groupChatReDto.getPageNum(),groupChatReDto.getPageSize(), Sort.Direction.ASC,"new_time");
        List<BmsUserChat> userChats = getGroupMember(pageable,business,groupChatReDto.getId());
        postHandGroupMemberBannerSayLogic(userChats);
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",bmsUserChatService.getBaseDao().countGroupMember(groupChatReDto.getId()));
        return ResultMapHelper.success(userChats,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    private void postHandGroupMemberBannerSayLogic(List<BmsUserChat> userChats) {
        if(userChats != null && userChats.size() > 0){
            for(BmsUserChat bmsUserChat : userChats){
                if(bmsUserChat.getIsBannerSay() != null) {
                    if (bmsUserChat.getIsBannerSay() == Constants.COMMON_FLAG_TRUE_INT) {
                        if (DateTimeUtils.getCurrentTime().getTime() > bmsUserChat.getCanSayTime().getTime()) {
                            bmsUserChat.setIsBannerSay(Constants.COMMON_FLAG_FALSE_INT);
                        }
                    }
                }
            }
            bmsUserChatService.getBaseDao().saveAll(userChats);
        }
    }


    public List<BmsUserChat> getGroupMember(Pageable pageable,BmsBusiness bmsBusiness,Integer chatId){
        List<BmsUserChat> userChats = bmsUserChatService.getBaseDao().findByGroupMember(chatId,pageable);
        System.out.println(userChats.size());
        if(userChats != null && userChats.size() > 0){
            Set<Integer> assistantIds = userChats.stream().filter(bmsUserChat -> Constants.ASSISTANT_ROLE_ID == bmsUserChat.getRoleId()).map(BmsUserChat::getUserId).collect(Collectors.toSet());
            Map<Integer,Integer> assistantRoleMap = bmsDxUserPermissionService.findUserHavingGroupPermission(assistantIds);
            for(BmsUserChat bmsUserChat : userChats){
                if(bmsUserChat.getRoleId() == Constants.BUSINESS_ROLE_ID
                        || bmsUserChat.getRoleId() == Constants.ASSISTANT_ROLE_ID){
                    bmsUserChat.setHeadImg(bmsBusiness.getLogoUrl());
                }
                if(assistantRoleMap.containsKey(bmsUserChat.getUserId())){
                    if(bmsUserChat.getRoleId() == Constants.ASSISTANT_ROLE_ID) {
                        bmsUserChat.setIsManager(Constants.COMMON_FLAG_TRUE_INT);
                    }
                }
            }
            setBmsGenUserChat(userChats);
        }
        return userChats;
    }

    private void setBmsGenUserChat(List<BmsUserChat> userChats) {
        if(userChats != null && userChats.size() > 0){
            Set<Integer> userIds = userChats.stream().filter(b -> Constants.GENERAL_USER_ROLE_ID == b.getRoleId()).map(BmsUserChat::getUserId).collect(Collectors.toSet());
            Integer businessId = userChats.get(0).getBusinessId();
            if(userIds.size() > 0) {
                //查询消费者消费次数和消费金额(买单订单)
                Map<Integer,Map<String,Object>> userConsumptionsCouponMap = bmsDxOrderStatusService.countCouponOrderSuccessNum(businessId,userIds);
                //查询消费者的消费次数和消费金额(核销订单)
                Map<Integer,Map<String,Object>> userConsumptionsGroupBuyMap = bmsDxOrderStatusService.countGroupOrderSuccessNum(businessId,userIds);
                //查询用户头像信息
                Map<Integer, BmsUser> bmsUserMap = bmsUserService.getUserByIds(userIds);
                for (BmsUserChat bmsUserChat : userChats) {
                    if(bmsUserChat.getRoleId() == Constants.GENERAL_USER_ROLE_ID) {
                        //设置买单订单消费金额和消费次数
                        if (userConsumptionsCouponMap.containsKey(bmsUserChat.getUserId())) {
                            Map<String, Object> consumptionMap = userConsumptionsCouponMap.get(bmsUserChat.getUserId());
                            bmsUserChat.setTotal(ArithUtil.add(Double.parseDouble(consumptionMap.get("total").toString()), bmsUserChat.getTotal()));
                            bmsUserChat.setConsumptionNum(bmsUserChat.getConsumptionNum() + Integer.parseInt(consumptionMap.get("num").toString()));
                        }
                        //设置团购订单消费金额和消费次数
                        if (userConsumptionsGroupBuyMap.containsKey(bmsUserChat.getUserId())) {
                            Map<String, Object> consumptionMap = userConsumptionsGroupBuyMap.get(bmsUserChat.getUserId());
                            bmsUserChat.setTotal(ArithUtil.add(Double.parseDouble(consumptionMap.get("total").toString()), bmsUserChat.getTotal()));
                            bmsUserChat.setConsumptionNum(bmsUserChat.getConsumptionNum() + Integer.parseInt(consumptionMap.get("num").toString()));
                        }
                        //设置头像
                        if (bmsUserMap.containsKey(bmsUserChat.getUserId())) {
                            BmsUser bmsUser = bmsUserMap.get(bmsUserChat.getUserId());
                            if (StringUtils.isNotBlank(bmsUser.getHeadImg())) {
                                bmsUserChat.setHeadImg(bmsUser.getHeadImg());
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public Map<String, Object> userGetGroupMembers(GroupChatReDto groupChatReDto) {
        BmsBusiness business = bmsBusinessService.getBusinessById(groupChatReDto.getBusinessId());
        if(business == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,ResultMsg.CODE_BUSINESS_NO_EXIST);
        }
        Integer chatId = groupChatReDto.getId();
        Pageable pageable = BmsCommonService.getPageable(groupChatReDto.getPageNum(),groupChatReDto.getPageSize(), Sort.Direction.ASC,"new_time");
        List<BmsUserChat> userChats = getGroupMember(pageable,business,chatId);
        postHandGroupMemberBannerSayLogic(userChats);
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",bmsUserChatService.getBaseDao().countGroupMember(groupChatReDto.getId()));
        return ResultMapHelper.success(userChats,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> shareToGroupChat(ParamsMap paramsMap) {
        final String mesText = "这是一条券库消息";
        Integer shareType = paramsMap.getInteger("shareType");
        Integer businessId = paramsMap.getInteger("businessId");
        Integer userId = paramsMap.getInteger("userIdentify");
        String mesTextDesc = paramsMap.getString("mesTextDesc");
        List<BmsDxGroupChat> bmsDxGroupChats = bmsDxGroupChatDao.findByBusinessIdAndIsDelete(businessId,Constants.COMMON_FLAG_FALSE_INT);
        if(!(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChats.get(0);
        if(shareType == Constants.CHAT_SHARE_COUPON){
            //券库分享
            Integer businessCouponId = paramsMap.getInteger("businessCouponId");
            BmsBusinessCoupon businessCoupon = bmsBusinessCouponService.getBaseDao().findByIdAndIsDelete(businessCouponId,Constants.COMMON_FLAG_FALSE_INT);
            bmsBusinessCouponService.setBusinessCoupons(businessCoupon);
            if(businessCoupon == null){
                return ResultMapHelper.result(ResultCode.CODE_ERROR_05,ResultMsg.CODE_ERROR_05);
            }
            //调用极光接口进行券分享
            Map<String,String> extras = new HashMap<>();
            List<ReGoupChat> reGoupChats = new LinkedList<>();
            if(StringUtils.isNotBlank(mesTextDesc)){
                extras.put("mesType",String.valueOf(Constants.CHAT_SHARE_TEXT));
                Map<String,Object> mesBody = new HashMap<>();
                mesBody.put("text",mesTextDesc);
                extras.put("mesBody",JSON.toJSONString(mesBody));
                if(!AuroraMessageUtils.sendGroupMessageByAdmin(bmsDxGroupChat.getGid(),AuroraMessageUtils.USER_PREFIX + userId.toString(),mesTextDesc,extras)){
                    return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
                }
                //插入一条记录记录下来
                ReGoupChat reGoupChat = new ReGoupChat();
                reGoupChat.setBusinessId(businessId);
                reGoupChat.setContent(JSON.toJSONString(extras));
                reGoupChat.setGroupId(bmsDxGroupChat.getId());
                reGoupChat.setMesType(Constants.CHAT_SHARE_COUPON);
                reGoupChat.setNewTime(new Date());
                reGoupChatService.getBaseDao().save(reGoupChat);
                reGoupChats.add(reGoupChat);
            }
            //分享券库消息
            extras.put("mesType",String.valueOf(Constants.CHAT_SHARE_COUPON));
            extras.put("mesBody",JSON.toJSONString(businessCoupon));
            if(AuroraMessageUtils.sendGroupMessageByAdmin(bmsDxGroupChat.getGid(),AuroraMessageUtils.USER_PREFIX + userId.toString(),mesText,extras)){
                //插入一条记录记录下来
                ReGoupChat reGoupChat = new ReGoupChat();
                reGoupChat.setBusinessId(businessId);
                reGoupChat.setContent(JSON.toJSONString(extras));
                reGoupChat.setGroupId(bmsDxGroupChat.getId());
                reGoupChat.setMesType(Constants.CHAT_SHARE_COUPON);
                reGoupChat.setNewTime(new Date());
                reGoupChatService.getBaseDao().save(reGoupChat);
                reGoupChats.add(reGoupChat);
                //进行极光推送
                postHandCreateGroupShare(bmsDxGroupChat,businessCoupon);
                return ResultMapHelper.success(reGoupChats,ResultMsg.HAND_SUCCESS);
            }
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
    }

    private void postHandCreateGroupShare(BmsDxGroupChat bmsDxGroupChat,BmsBusinessCoupon bmsBusinessCoupon) {
        //给群里的用户每个人发一条通知
        BmsCommonService.getApplicationContext().publishEvent(new GroupShareEvent("groupShare",bmsDxGroupChat,bmsBusinessCoupon));
    }

    @Override
    public Map<String, Object> userJoinGroup(GroupChatReDto groupChatReDto) {
        Integer userId = Integer.parseInt(groupChatReDto.getUserId());
        Integer businessId = groupChatReDto.getBusinessId();
        List<BmsDxGroupChat> bmsDxGroupChats = bmsDxGroupChatDao.findByBusinessIdAndIsDelete(businessId,Constants.COMMON_FLAG_FALSE_INT);
        if(!(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChats.get(0);
        //查询用户是否进群
        /*List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findByUserIdAndRoleIdAndChatId(userId,Constants.GENERAL_USER_ROLE_ID,bmsDxGroupChat.getId());
        if(bmsUserChats != null && bmsUserChats.size() > 0){
            return ResultMapHelper.success(bmsDxGroupChat,ResultMsg.HAND_SUCCESS);
        }*/
        //是否达到门槛
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("businessId",bmsDxGroupChat.getBusinessId());
        Set<Integer> statuses = new HashSet<>();
        statuses.add(Constants.PAY_COMPLETE);
        statuses.add(Constants.ALREADY_USE);
        statuses.add(Constants.REFUND_COMPLETE);
        conditionMap.put("status_IN",statuses);
        long ret = bmsDxOrderStatusService.getBaseDao().count(new SpecificationUtils(conditionMap));
        /*if(ret == 0){
            return ResultMapHelper.result(ResultCode.CODE_NO_HAVING_JOIN_GROUP_CHANGE,ResultMsg.CODE_NO_HAVING_JOIN_GROUP_CHANGE);
        }*/
        //首先往极光注册用户
        BmsUser bmsUser = TokenManager.getUser(userId);
        AuroraMessageUtils.registerGeneralUsers(bmsUser);
        //刷新用户信息
        AuroraMessageUtils.updateGeneralUsers(bmsUser,Constants.GENERAL_USER_ROLE_ID);
        //加入极光群
        if(AuroraMessageUtils.genUserJoinGroup(bmsDxGroupChat.getGid(),bmsUser)){
            //同步数据库
            List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findByUserIdAndRoleIdAndChatId(userId,Constants.GENERAL_USER_ROLE_ID,bmsDxGroupChat.getId());
            if(!(bmsUserChats != null && bmsUserChats.size() > 0)){
                BmsUserChat bmsUserChat = new BmsUserChat();
                bmsUserChat.setUserId(userId);
                bmsUserChat.setRoleId(Constants.GENERAL_USER_ROLE_ID);
                bmsUserChat.setChatId(bmsDxGroupChat.getId());
                bmsUserChat.setBusinessId(businessId);
                bmsUserChat.setNewTime(new Date());
                bmsUserChat.setNameInGroupChat(BmsUserService.getLoginName(bmsUser));
                bmsUserChatService.getBaseDao().save(bmsUserChat);
                //群人数累加
                Integer num = bmsUserChatService.getBaseDao().countGroupMember(bmsDxGroupChat.getId());
                bmsDxGroupChat.setGroupNum(num);
                bmsDxGroupChatDao.save(bmsDxGroupChat);
            }
            //同步关注
            bmsUserBusinessFocusService.focusBusiness(userId,businessId);
            return ResultMapHelper.success(bmsDxGroupChat,ResultMsg.HAND_SUCCESS);
        }
        return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
    }

    @Override
    public Map<String, Object> testSendGroupChat(ParamsMap paramsMap) {
        Integer way = paramsMap.getInteger("way");
        if(way == 1) {
            String gid = "41036819";
            String userName = "sy_650";
            final String mesText = "这是一条券库消息";
            BmsBusinessCoupon businessCoupon = bmsBusinessCouponService.getBaseDao().findByIdAndIsDelete(1, Constants.COMMON_FLAG_FALSE_INT);
            Map<String, String> extras = new HashMap<>();
            extras.put("mesType", String.valueOf(Constants.CHAT_SHARE_COUPON));
            extras.put("mesBody", JSON.toJSONString(businessCoupon));
            AuroraMessageUtils.sendGroupMessageByAdmin(gid, userName, mesText, extras);
        }else {

        }
        return ResultMapHelper.success(null,"ok");
    }

    @Override
    public Map<String, Object> getGroupData(GroupChatReDto groupChatReDto) {
        Integer chatId = groupChatReDto.getId();
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChatDao.findByIdAndIsDelete(chatId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupChat == null){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        //获取群成员
        Pageable pageable = BmsCommonService.getPageable(1,groupChatReDto.getPageSize(), Sort.Direction.ASC,"new_time");
        BmsBusiness business = bmsBusinessService.getBusinessById(bmsDxGroupChat.getBusinessId());
        List<BmsUserChat> bmsUserChats = getGroupMember(pageable,business,bmsDxGroupChat.getId());
        bmsDxGroupChat.setUserMember(bmsUserChats);
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("count",bmsUserChatService.getBaseDao().countGroupMember(groupChatReDto.getId()));
        //获取最新一条群公告
        bmsDxGroupChat.setBmsChatAnnouns(bmsChatAnnounService.getLatestAnnon(chatId));
        return ResultMapHelper.success(bmsDxGroupChat,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> userGetMyGroup(GroupChatReDto groupChatReDto) {
        Integer userId = Integer.parseInt(groupChatReDto.getUserId());
        //查询该用户所有群
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("roleId",Constants.GENERAL_USER_ROLE_ID);
        Pageable pageable = BmsCommonService.getPageable(groupChatReDto.getPageNum(),groupChatReDto.getPageSize(), Sort.Direction.DESC,"isTop");
        List<BmsDxGroupChat> bmsDxGroupChats = new LinkedList<>();
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findAll(new SpecificationUtils(conditionMap),pageable).getContent();
        Set<Integer> chatIds = bmsUserChats.stream().map(BmsUserChat::getChatId).collect(Collectors.toSet());
        if(chatIds.size() > 0){
            LinkedList<Integer> orderChatIds = new LinkedList<>();
            for(BmsUserChat bmsUserChat : bmsUserChats){
                orderChatIds.add(bmsUserChat.getChatId());
            }
            List<BmsDxGroupChat> chats = bmsDxGroupChatDao.findByIdInAndIsDelete(chatIds,Constants.COMMON_FLAG_FALSE_INT);
            if(chats != null && chats.size() > 0){
                Map<Integer,BmsDxGroupChat> bmsDxGroupChatMap = new HashMap<>();
                for(BmsDxGroupChat bmsDxGroupChat : chats){
                    bmsDxGroupChatMap.put(bmsDxGroupChat.getId(),bmsDxGroupChat);
                }
                for(Integer chatId : orderChatIds){
                    if(bmsDxGroupChatMap.containsKey(chatId)){
                        bmsDxGroupChats.add(bmsDxGroupChatMap.get(chatId));
                    }
                }
            }
        }
        return ResultMapHelper.success(bmsDxGroupChats,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> userGetGroupData(GroupChatReDto groupChatReDto) {
        Integer chatId = groupChatReDto.getId();
        Integer userId = Integer.parseInt(groupChatReDto.getUserId());
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChatDao.findByIdAndIsDelete(chatId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupChat == null){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        //查询商家信息
        BmsBusiness business = bmsBusinessService.getBusinessById(bmsDxGroupChat.getBusinessId());
        if(business != null){
            bmsDxGroupChat.setBmsBusiness(business);
        }
        //查看自己的信息
        Pageable pageable = BmsCommonService.getPageable(1,1);
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("roleId",Constants.GENERAL_USER_ROLE_ID);
        conditionMap.put("chatId",chatId);
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findAll(new SpecificationUtils(conditionMap),pageable).getContent();
        if(bmsUserChats != null && bmsUserChats.size() > 0){
            bmsDxGroupChat.setUserMember(bmsUserChats);
        }
        //获取最新一条群公告
        bmsDxGroupChat.setBmsChatAnnouns(bmsChatAnnounService.getLatestAnnon(chatId));
        return ResultMapHelper.success(bmsDxGroupChat,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> userBackGroup(GroupChatReDto groupChatReDto) {
        Integer chatId = groupChatReDto.getId();
        Integer userId = Integer.parseInt(groupChatReDto.getUserId());
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChatDao.findByIdAndIsDelete(chatId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupChat == null){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        //查询用户是否进群
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findByUserIdAndRoleIdAndChatId(userId,Constants.GENERAL_USER_ROLE_ID,bmsDxGroupChat.getId());
        if(!(bmsUserChats != null && bmsUserChats.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_USER_BACK_GROUP,ResultMsg.CODE_USER_BACK_GROUP);
        }
        //极光退群
        //if(AuroraMessageUtils.genUserBackGroup(bmsDxGroupChat.getGid(),bmsUserChats.get(0))){
        //数据库退群
        BmsUserChat bmsUserChat = bmsUserChats.get(0);
        bmsUserChatService.getBaseDao().delete(bmsUserChat);
        return ResultMapHelper.success(bmsUserChat,ResultMsg.HAND_SUCCESS);
        //}
        //return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
    }

    @Override
    public Map<String, Object> groupAnnounPro(GroupChatReDto groupChatReDto) {
        Integer chatId = groupChatReDto.getId();
        Integer businessId = groupChatReDto.getBusinessId();
        Integer userId = Integer.parseInt(groupChatReDto.getUserId());
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChatDao.findByIdAndIsDelete(chatId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupChat == null){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        Set<Integer> roleIds = new HashSet<>();
        if(businessId == null){
            roleIds.add(Constants.GENERAL_USER_ROLE_ID);
        }else {
            roleIds.add(Constants.BUSINESS_ROLE_ID);
            roleIds.add(Constants.ASSISTANT_ROLE_ID);
        }
        Integer roleId;
        //获取该群最新一条公告
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("isSeen",Constants.COMMON_FLAG_FALSE_INT);
        resultMap.put("bmsChatAnnouns",new ArrayList<>());
        List<BmsChatAnnoun> bmsChatAnnouns = bmsChatAnnounService.getLatestAnnon(chatId);
        if(bmsChatAnnouns != null && bmsChatAnnouns.size() > 0){
            BmsChatAnnoun bmsChatAnnoun = bmsChatAnnouns.get(0);
            List<BmsDxClientRole> bmsDxClientRoles = bmsDxClientRoleService.getUserClienRole(userId,roleIds);
            if(bmsDxClientRoles != null && bmsDxClientRoles.size() > 0){
                roleId = bmsDxClientRoles.get(0).getRoleId();
                String redisKey = Constants.REDIS_KEY_USER_HAVE_SEE_ANNOUN;
                String recordKey = roleId.toString() + ":" + userId.toString() + ":" + bmsDxGroupChat.getId();
                if(redisTemplate.opsForHash().hasKey(redisKey,recordKey)){
                    Integer announId = Integer.parseInt(redisTemplate.opsForHash().get(redisKey,recordKey).toString());
                    if(announId.intValue() != bmsChatAnnoun.getId().intValue()){
                        redisTemplate.opsForHash().put(redisKey,recordKey,bmsChatAnnoun.getId().toString());
                    }else {
                        resultMap.put("isSeen",Constants.COMMON_FLAG_TRUE_INT);
                    }
                }else {
                    redisTemplate.opsForHash().put(redisKey,recordKey,bmsChatAnnoun.getId().toString());
                }
            }
            resultMap.put("bmsChatAnnouns",bmsChatAnnouns);
        }
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> startRemind(GroupChatReDto groupChatReDto) {
        Integer userId = Integer.parseInt(groupChatReDto.getUserId());
        Integer gid = groupChatReDto.getId();
        Integer remindStatus = groupChatReDto.getRemindStatus();
        Map<String,Object> conditonMap = new HashMap<>();
        conditonMap.put("userId",userId);
        conditonMap.put("chatId",gid);
        conditonMap.put("roleId",Constants.GENERAL_USER_ROLE_ID);
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findAll(new SpecificationUtils(conditonMap));
        if(!(bmsUserChats != null && bmsUserChats.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_USER_BACK_GROUP,ResultMsg.CODE_USER_BACK_GROUP);
        }
        BmsUserChat bmsUserChat = bmsUserChats.get(0);
        bmsUserChat.setIsStartRemind(remindStatus);
        bmsUserChatService.getBaseDao().save(bmsUserChat);
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> banned(ParamsMap paramsMap) {
        Map<Integer,Integer> bannerMap = new HashMap<>();
        //第一次禁言10分钟
        bannerMap.put(1,10 * 60);
        //第二次禁言1个小时
        bannerMap.put(2,60 * 60);
        //第三次禁言6个小时
        bannerMap.put(3,60 * 60 * 6);
        //第四次禁言12个小时
        bannerMap.put(4,60 * 60 * 12);
        //第五次禁言6个小时
        bannerMap.put(5,60 * 60 * 24);
        bannerMap.put(6,60 * 60 * 24 * 3);
        final int MAX_BANNER_NUM = 6;
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer businessId = paramsMap.getInteger("businessId");
        Integer bannerUser = paramsMap.getInteger("bannerUser");
        Integer bannerUserRole = paramsMap.getInteger("bannerUserRole");
        Integer chatId = paramsMap.getInteger("chatId");
        Integer status = paramsMap.getInteger("status");
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessUserAuth(userId,businessId,Constants.GROUP_CHAT_PERMISSION);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Map<Integer,String> chatIdToGidMap = new HashMap<>();
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChatDao.findByIdAndIsDelete(chatId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupChat == null){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        //添加映射
        chatIdToGidMap.put(bmsDxGroupChat.getId(),bmsDxGroupChat.getGid());
        //查看用户是否在群里
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findByUserIdAndRoleIdAndChatId(bannerUser,bannerUserRole,chatId);
        if(!(bmsUserChats != null && bmsUserChats.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_USER_BACK_GROUP,ResultMsg.CODE_USER_BACK_GROUP);
        }
        //禁言成功后修改逻辑
        BmsUserChat bmsUserChat = bmsUserChats.get(0);
        bmsUserChat.setIsBannerSay(status);
        BmsUser bmsUser = TokenManager.getUser(bannerUser);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,ResultMsg.CODE_USER_NO_EXIST);
        }
        List<BmsUserChat> bannerData = new LinkedList<>();
        if(status == Constants.COMMON_FLAG_FALSE_INT){
            bmsUserChat.setCanSayTime(null);
        }else {
            if(bmsUserChat.getBannerNum() == null){
                bmsUserChat.setBannerNum(Constants.COMMON_FLAG_FALSE_INT);
            }
            if(bmsUserChat.getBannerNum() < MAX_BANNER_NUM) {
                bmsUserChat.setBannerNum(bmsUserChat.getBannerNum() + 1);
            }
            if(bannerMap.containsKey(bmsUserChat.getBannerNum())){
                bmsUserChat.setCanSayTime(DateTimeUtils.addSecond(new Date(),bannerMap.get(bmsUserChat.getBannerNum())));
            }
            bannerData.add(bmsUserChat);
        }
        //同时找出在其他群被禁言的数据
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",bannerUser);
        conditionMap.put("chatId_NEQ",chatId);
        conditionMap.put("roleId",bannerUserRole);
        conditionMap.put("isBannerSay",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("canSayTime_GTT",new Date());
        List<BmsUserChat> buc = bmsUserChatService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        if(buc != null && buc.size() > 0){
            bannerData.addAll(buc);
            Set<Integer> chatIds = buc.stream().map(BmsUserChat::getChatId).collect(Collectors.toSet());
            if(chatIds.size() > 0){
                List<BmsDxGroupChat> bmsDxGroupChats = bmsDxGroupChatDao.findByIdIn(chatIds);
                if(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0){
                    for(BmsDxGroupChat bd : bmsDxGroupChats){
                        chatIdToGidMap.put(bd.getId(),bd.getGid());
                    }
                }
            }
        }
        if(!AuroraMessageUtils.updateUsersBannerSay(bmsUser,bannerUserRole,chatIdToGidMap,bannerData)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
        }
        bmsUserChatService.getBaseDao().save(bmsUserChat);
        return ResultMapHelper.success(bmsUserChat,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> isTopChat(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer chatId = paramsMap.getInteger("chatId");
        Integer isTop = paramsMap.getInteger("isTop");
        Map<String,Object> conditonMap = new HashMap<>();
        conditonMap.put("userId",userId);
        conditonMap.put("chatId",chatId);
        conditonMap.put("roleId",Constants.GENERAL_USER_ROLE_ID);
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findAll(new SpecificationUtils(conditonMap));
        if(!(bmsUserChats != null && bmsUserChats.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_USER_BACK_GROUP,ResultMsg.CODE_USER_BACK_GROUP);
        }
        BmsUserChat bmsUserChat = bmsUserChats.get(0);
        bmsUserChat.setIsTop(isTop);
        bmsUserChatService.getBaseDao().save(bmsUserChat);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("topTime",new Date());
        return ResultMapHelper.success(resultMap,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> userGetQualityGroup(ParamsMap paramsMap) {
        final int DEFAULT_RECOMMEND_NUM = 15;
        Integer userId = paramsMap.getInteger("userIdentify");
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        //查询该用户进入的群
        Set<Integer> chatIds = new HashSet<>();
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findByUserIdAndRoleId(userId,Constants.GENERAL_USER_ROLE_ID);
        if(bmsUserChats != null && bmsUserChats.size() > 0){
            chatIds.addAll(bmsUserChats.stream().map(BmsUserChat::getChatId).collect(Collectors.toSet()));
        }
        Map<String,Object> conditionMap = new HashMap<>();
        if(chatIds.size() > 0) {
            conditionMap.put("id_NIN", chatIds);
        }
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsDxGroupChat> bmsDxGroupChats = bmsDxGroupChatDao.findAll(new SpecificationUtils(conditionMap));
        List<BmsDxGroupChat> resultDxGroupChat = new ArrayList<>();
        if(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0){
            Set<Integer> businessIds = bmsDxGroupChats.stream().map(BmsDxGroupChat::getBusinessId).collect(Collectors.toSet());
            Map<Integer, List<BmsDxGroupChat>> groupMap = new HashMap<>();
            for (BmsDxGroupChat bmsDxGroupChat : bmsDxGroupChats) {
                if (!groupMap.containsKey(bmsDxGroupChat.getBusinessId())) {
                    groupMap.put(bmsDxGroupChat.getBusinessId(), new ArrayList<>());
                }
                groupMap.get(bmsDxGroupChat.getBusinessId()).add(bmsDxGroupChat);
            }
            Map<String, Object> businessSearchMap = new HashMap<>();
            businessSearchMap.put("id_IN", businessIds);
            businessSearchMap.put("isDelete", Constants.COMMON_FLAG_FALSE_INT);
            businessSearchMap.put("isUnload", Constants.COMMON_FLAG_FALSE_INT);
            businessSearchMap.put("addrCity", addrCity);
            businessSearchMap.put("addrDistrict", addrDistrict);
            List<BmsBusiness> bmsBusinesses = bmsBusinessService.getBaseDao().findAll(new SpecificationUtils(businessSearchMap));
            if (bmsBusinesses != null && bmsBusinesses.size() > 0) {
                for (BmsBusiness business : bmsBusinesses) {
                    if (StringUtils.isNotBlank(business.getLatitude()) && StringUtils.isNotBlank(business.getLongitude())
                            && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
                        double lat = Double.parseDouble(business.getLatitude());
                        double lnt = Double.parseDouble(business.getLongitude());
                        double distance = LocationUtils.getDistance(lat, lnt, Double.parseDouble(latitude), Double.parseDouble(longitude));
                        //公里数以内
                        business.setDistance(distance);
                        //取出那个团购券
                        Integer businessId = business.getId();
                        if (groupMap.containsKey(businessId)) {
                            List<BmsDxGroupChat> buys = groupMap.get(businessId);
                            for (BmsDxGroupChat bmsDxGroupChat : buys) {
                                bmsDxGroupChat.setBmsBusiness(business);
                                resultDxGroupChat.add(bmsDxGroupChat);
                                chatIds.add(bmsDxGroupChat.getId());
                            }
                        }
                    }
                }
            }
            if(resultDxGroupChat != null && resultDxGroupChat.size() > 0){
                //排序
                Collections.sort(resultDxGroupChat,new Comparator<BmsDxGroupChat>() {
                    @Override
                    public int compare(BmsDxGroupChat o1, BmsDxGroupChat o2) {
                        if(o1.getBmsBusiness() == null || o2.getBmsBusiness() == null) {
                            return -1;
                        }
                        if (o1.getBmsBusiness().getDistance() < o2.getBmsBusiness().getDistance()) {
                            return 1;
                        } else if (o1.getBmsBusiness().getDistance() == o2.getBmsBusiness().getDistance()) {
                            return 0;
                        }
                        return 1;
                    }
                });
                //截取15条记录
                int subNum = DEFAULT_RECOMMEND_NUM;
                if(resultDxGroupChat.size() < subNum){
                    subNum = resultDxGroupChat.size();
                }
                resultDxGroupChat = resultDxGroupChat.subList(0,subNum);
            }
            if(resultDxGroupChat.size() < DEFAULT_RECOMMEND_NUM){
                //补充15条
                conditionMap.clear();
                if(chatIds.size() > 0){
                    conditionMap.put("id_NIN",chatIds);
                }
                conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
                Pageable pageable = BmsCommonService.getPageable(1,DEFAULT_RECOMMEND_NUM - resultDxGroupChat.size(), Sort.Direction.DESC,"groupNum");
                Page<BmsDxGroupChat> bmsDxGroupChatPage = bmsDxGroupChatDao.findAll(new SpecificationUtils(conditionMap),pageable);
                List<BmsDxGroupChat> bs = bmsDxGroupChatPage.getContent();
                postHandGroupChatBmsBusiness(bs);
                resultDxGroupChat.addAll(bmsDxGroupChatPage.getContent());
            }
        }
        //System.out.println(resultDxGroupChat.size());
        return ResultMapHelper.success(resultDxGroupChat,ResultMsg.MSG_GET_SUCCESS);
    }

    private void postHandGroupChatBmsBusiness(List<BmsDxGroupChat> bs) {
        if(bs != null && bs.size() > 0){
            Set<Integer> businessIds = bs.stream().map(BmsDxGroupChat::getBusinessId).collect(Collectors.toSet());
            Map<Integer,BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIds(businessIds);
            for(BmsDxGroupChat bmsDxGroupChat : bs){
                 if(bmsBusinessMap.containsKey(bmsDxGroupChat.getBusinessId())){
                     bmsDxGroupChat.setBmsBusiness(bmsBusinessMap.get(bmsDxGroupChat.getBusinessId()));
                 }
            }
        }
    }

    @Override
    public Map<String, Object> updateMyNameInGroup(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer chatId = paramsMap.getInteger("chatId");
        String updateName = paramsMap.getString("updateName");
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findByUserIdAndRoleIdAndChatId(userId,Constants.GENERAL_USER_ROLE_ID,chatId);
        if(!(bmsUserChats != null && bmsUserChats.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_USER_BACK_GROUP,ResultMsg.CODE_USER_BACK_GROUP);
        }
        BmsUserChat bmsUserChat = bmsUserChats.get(0);
        bmsUserChat.setNameInGroupChat(updateName);
        bmsUserChatService.getBaseDao().save(bmsUserChat);
        //同步到极光
        //BmsUser bmsUser = TokenManager.getUser(userId);
        //bmsUser.setLoginName(updateName);
        //AuroraMessageUtils.updateGeneralUsers(bmsUser,Constants.GENERAL_USER_ROLE_ID);
        return ResultMapHelper.success(bmsUserChat,ResultMsg.HAND_SUCCESS);
    }

    @Override
    @Transactional
    public Map<String, Object> removeGroupMember(ParamsMap paramsMap) {
        Integer removeUserId = paramsMap.getInteger("removeUserId");
        Integer chatId = paramsMap.getInteger("chatId");
        BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChatDao.findByIdAndIsDelete(chatId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupChat == null){
            return ResultMapHelper.result(ResultCode.CODE_GROUP_CHAT_IS_NO_EXIST,ResultMsg.MSG_GROUP_CHAT_IS_NO_EXIST);
        }
        List<BmsUserChat> bmsUserChats = bmsUserChatService.getBaseDao().findByUserIdAndRoleIdAndChatId(removeUserId,Constants.GENERAL_USER_ROLE_ID,chatId);
        if(!(bmsUserChats != null && bmsUserChats.size() > 0)){
            BmsUserChat bmsUserChat = new BmsUserChat();
            bmsUserChat.setUserId(removeUserId);
            bmsUserChats.add(bmsUserChat);
        }
        BmsUserChat bmsUserChat = bmsUserChats.get(0);
        //极光移除
        if(!AuroraMessageUtils.genUserBackGroup(bmsDxGroupChat.getGid(),bmsUserChat)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
        }
        //数据库移除
        if(bmsUserChat.getId() != null) {
            bmsUserChatService.getBaseDao().delete(bmsUserChat);
            //群成员人数减1
            if(bmsDxGroupChat.getGroupNum() > 1) {
                bmsDxGroupChat.setGroupNum(bmsDxGroupChat.getGroupNum() - 1);
                bmsDxGroupChatDao.save(bmsDxGroupChat);
            }
        }
        return ResultMapHelper.success(bmsUserChat,ResultMsg.HAND_SUCCESS);
    }
}
